package lc;
import java.util.*;
import org.junit.*;

public class Ex718 {
    class Solution {
        public int findLength(int[] nums1, int[] nums2) {
            int m = nums1.length, n = nums2.length;
            if (m > n) {
                return findLength(nums2, nums1);
            }
            Map<Integer, List<Integer>> map = new HashMap<>();
            for (int i = 0; i < n; i++) {
                if (map.containsKey(nums2[i])) {
                    map.get(nums2[i]).add(i);
                } else {
                    List<Integer> list = new ArrayList<>();
                    list.add(i);
                    map.put(nums2[i], list);
                }
            }
    
            for (int i = m; i > 0; i--) {
                for (int j = 0; j < m; j++) {
                    if (m - j < i) {
                        break;
                    }
                    List<Integer> cur = map.get(nums1[j]);
                    if (cur == null) {
                        continue;
                    }
                    for (int k: cur) {
                        if (n - k < i) {
                            break;
                        }
                        boolean flag = true;
                        for (int a = 0; a < i; a++) {
                            if (nums1[j + a] != nums2[k + a]) {
                                flag = false;
                                break;
                            }
                        }
                        if (flag) {
                            return i;
                        }
                    }
                }
            }
            return 0;
    
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        int[] nums1 = new int[]{1,2,3,2,1}, nums2 = {3,2,1,4,7};
        System.out.println(s.findLength(nums1, nums2));
    }
}
